<template>
  <div class="news-detail-container">
    <el-card class="news-detail-card" v-loading="loading">
      <!-- 新闻内容 -->
      <div v-if="newsDetail" class="news-wrapper">
        <div class="news-header">
          <h1 class="news-title">{{ newsDetail.title }}</h1>
          <div class="news-meta">
            <div class="meta-left">
              <span class="news-date"><el-icon><Calendar /></el-icon> {{ formatDate(newsDetail.publishTime) }}</span>
              <span class="news-author" v-if="newsDetail.author"><el-icon><User /></el-icon> {{ newsDetail.author }}</span>
              <span class="news-views"><el-icon><View /></el-icon> {{ newsDetail.viewCount }}</span>
            </div>
            
            <div class="news-categories">
              <el-tag
                v-for="category in newsDetail.categories"
                :key="category.id"
                size="small"
                effect="plain"
                class="category-tag"
              >
                {{ category.name }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <!-- 封面图片 -->
        <div class="news-cover" v-if="newsDetail.coverImage">
          <el-image :src="newsDetail.coverImage" alt="封面图片" fit="cover"></el-image>
        </div>
        
        <!-- 新闻内容 -->
        <div class="news-content" v-html="newsDetail.content"></div>
        
        <!-- 分享按钮 -->
        <div class="news-actions">
          <el-button type="primary" plain round size="small" @click="goBack">
            <el-icon><Back /></el-icon> 返回列表
          </el-button>
          <div class="share-buttons">
            <span class="share-label">分享到：</span>
            <el-button circle size="small" type="primary"><el-icon><Connection /></el-icon></el-button>
            <el-button circle size="small" type="success"><el-icon><ChatDotRound /></el-icon></el-button>
            <el-button circle size="small" type="warning"><el-icon><Star /></el-icon></el-button>
          </div>
        </div>
        
        <!-- 评论区 -->
        <div class="comment-section">
          <div class="section-header">
            <h3><el-icon><ChatLineRound /></el-icon> 评论区</h3>
            <span class="comment-count">{{ commentTotal }}条评论</span>
          </div>
          
          <!-- 评论表单 -->
          <div class="comment-form" v-if="isLoggedIn">
            <div class="user-comment-avatar" v-if="user && user.avatar">
              <img :src="user.avatar" alt="用户头像">
            </div>
            <div class="user-comment-input">
              <el-input
                v-model="commentForm.content"
                type="textarea"
                :rows="3"
                placeholder="请输入您的评论"
                resize="none"
              ></el-input>
              <div class="comment-form-footer">
                <el-button type="primary" @click="submitComment" :loading="submitting" round>
                  <el-icon><Position /></el-icon> 发表评论
                </el-button>
              </div>
            </div>
          </div>
          <div v-else class="login-notice">
            <el-alert
              type="info"
              show-icon
              :closable="false"
            >
              请先<el-button type="primary" size="small" @click="goToLogin" plain>登录</el-button>后再评论
            </el-alert>
          </div>
          
          <!-- 评论列表 -->
          <div class="comment-list">
            <el-divider>
              <el-icon><ChatDotSquare /></el-icon> 全部评论
            </el-divider>
            
            <div v-if="comments.length === 0" class="no-comments">
              <el-empty description="暂无评论，快来发表您的看法吧"></el-empty>
            </div>
            
            <div v-else>
              <div class="comment-item" v-for="comment in comments" :key="comment.id">
                <div class="comment-user">
                  <div class="user-avatar">
                    <img :src="comment.userAvatar || defaultAvatar" alt="用户头像">
                  </div>
                  <div class="user-info">
                    <span class="user-name">{{ comment.userName || '用户' + comment.userId }}</span>
                    <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                  </div>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
                <div class="comment-actions" v-if="canDeleteComment(comment)">
                  <el-button type="danger" size="small" plain round @click="deleteComment(comment.id)">
                    <el-icon><Delete /></el-icon> 删除
                  </el-button>
                </div>
              </div>
              
              <!-- 分页 -->
              <div class="comment-pagination">
                <el-pagination
                  layout="prev, pager, next"
                  :total="commentTotal"
                  :page-size="commentPageSize"
                  :current-page="commentPage"
                  @current-change="handleCommentPageChange"
                  hide-on-single-page
                  background
                ></el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 新闻不存在 -->
      <el-empty v-else description="新闻不存在或已被删除">
        <template #description>
          <span>新闻不存在或已被删除</span>
        </template>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, User, View, ChatLineRound, ChatDotRound, 
  ChatDotSquare, Position, Back, Connection, Star, Delete } from '@element-plus/icons-vue'
import axios from '../../../utils/axios'

const route = useRoute()
const router = useRouter()
const defaultAvatar = '/static/default-avatar.png'

// 数据
const newsDetail = ref(null)
const loading = ref(false)
const comments = ref([])
const commentTotal = ref(0)
const commentPage = ref(1)
const commentPageSize = ref(10)
const submitting = ref(false)

// 用户信息
const user = computed(() => {
  return JSON.parse(sessionStorage.getItem('user')) || null
})

const isLoggedIn = computed(() => {
  return !!user.value
})

// 评论表单
const commentForm = ref({
  content: '',
  newsId: null,
  userId: null
})

// 获取新闻详情
const getNewsDetail = async () => {
  const newsId = route.params.id
  if (!newsId) {
    ElMessage.error('新闻ID不能为空')
    return
  }
  
  loading.value = true
  try {
    const res = await axios.get(`/news/${newsId}`)
    if (res.data.code === 200) {
      newsDetail.value = res.data.result
      // 初始化评论表单
      commentForm.value.newsId = parseInt(newsId)
      commentForm.value.userId = user.value ? user.value.id : null
    } else {
      ElMessage.error(res.data.message || '获取新闻详情失败')
    }
  } catch (error) {
    console.error('获取新闻详情失败', error)
    ElMessage.error('获取新闻详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const getComments = async () => {
  const newsId = route.params.id
  if (!newsId) return
  
  try {
    const res = await axios.get(`/news/comment/list/${newsId}`, {
      params: {
        pageNum: commentPage.value,
        pageSize: commentPageSize.value
      }
    })
    
    if (res.data.code === 200 && res.data.result) {
      comments.value = res.data.result.records || []
      commentTotal.value = res.data.result.total || 0
    }
  } catch (error) {
    console.error('获取评论列表失败', error)
    ElMessage.error('获取评论列表失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentForm.value.content.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  
  submitting.value = true
  try {
    const res = await axios.post('/news/comment', commentForm.value)
    if (res.data.code === 200) {
      ElMessage.success('评论成功')
      commentForm.value.content = '' // 清空评论
      commentPage.value = 1 // 回到第一页
      await getComments() // 刷新评论列表
    } else {
      ElMessage.error(res.data.message || '评论失败')
    }
  } catch (error) {
    console.error('提交评论失败', error)
    ElMessage.error('提交评论失败')
  } finally {
    submitting.value = false
  }
}

// 删除评论
const deleteComment = async (commentId) => {
  ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.delete(`/news/comment/${commentId}`, {
        params: { userId: user.value.id }
      })
      
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        await getComments() // 刷新评论列表
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除评论失败', error)
      ElMessage.error('删除评论失败')
    }
  }).catch(() => {})
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 判断是否可以删除评论
const canDeleteComment = (comment) => {
  return user.value && (user.value.id === comment.userId || user.value.roleId === 4)
}

// 评论分页变化
const handleCommentPageChange = (page) => {
  commentPage.value = page
  getComments()
}

onMounted(() => {
  getNewsDetail()
  getComments()
})
</script>

<style scoped>
.news-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 20px;
}

.news-detail-card {
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.news-wrapper {
  padding: 10px;
}

.news-header {
  margin-bottom: 30px;
}

.news-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  line-height: 1.4;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
  flex-wrap: wrap;
  gap: 10px;
}

.meta-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.news-date, .news-author, .news-views {
  display: flex;
  align-items: center;
  gap: 4px;
}

.news-categories {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.category-tag {
  border-radius: 16px;
}

.news-cover {
  margin: 0 -10px 30px;
  border-radius: 8px;
  overflow: hidden;
  max-height: 500px;
}

.news-cover .el-image {
  width: 100%;
  display: block;
}

.news-content {
  line-height: 1.8;
  color: #333;
  font-size: 16px;
  margin-bottom: 40px;
}

.news-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 16px 0;
  border-radius: 8px;
}

.news-content :deep(p) {
  margin: 16px 0;
}

.news-content :deep(h1), .news-content :deep(h2), .news-content :deep(h3) {
  margin: 24px 0 16px;
  font-weight: 600;
  color: #303133;
}

.news-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30px 0;
  flex-wrap: wrap;
  gap: 20px;
}

.share-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.share-label {
  font-size: 14px;
  color: #606266;
}

.comment-section {
  margin-top: 50px;
  border-top: 1px solid #ebeef5;
  padding-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.comment-count {
  font-size: 14px;
  color: #909399;
}

.comment-form {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.user-comment-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  border: 1px solid #ebeef5;
}

.user-comment-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-comment-input {
  flex: 1;
}

.comment-form-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.login-notice {
  margin: 20px 0 30px;
}

.comment-list {
  margin-top: 30px;
}

.no-comments {
  padding: 40px 0;
}

.comment-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.comment-item:hover {
  background-color: #f9fafc;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
  border: 1px solid #ebeef5;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  font-size: 15px;
  line-height: 1.6;
  color: #606266;
  word-break: break-word;
  padding-left: 52px;
  margin-bottom: 10px;
}

.comment-actions {
  padding-left: 52px;
  display: flex;
  justify-content: flex-end;
}

.comment-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .news-detail-container {
    padding: 15px 10px;
  }
  
  .news-title {
    font-size: 22px;
  }
  
  .news-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .news-categories {
    margin-top: 10px;
    margin-left: 0;
  }
  
  .comment-form {
    flex-direction: column;
  }
  
  .user-comment-avatar {
    display: none;
  }
  
  .comment-content {
    padding-left: 0;
  }
  
  .comment-actions {
    padding-left: 0;
  }
}
</style> 